package pers.zh.parking.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;

import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.Poi;
import com.amap.api.navi.AmapNaviPage;
import com.amap.api.navi.AmapNaviParams;
import com.amap.api.navi.AmapNaviType;
import com.amap.api.navi.INaviInfoCallback;

import pers.zh.parking.amap.NaviInfoCallback;
import pers.zh.parking.config.GlobalConfiguration;
import pers.zh.parking.mvp.ui.activity.MapActivity;
import pers.zjc.commonlibs.util.AppUtils;

public class MyUtils {

    public static String sHA1(Context context) {
        try {
            PackageInfo info = context.getPackageManager()
                                      .getPackageInfo(context.getPackageName(),
                                              PackageManager.GET_SIGNATURES);
            byte[] cert = info.signatures[0].toByteArray();
            MessageDigest md = MessageDigest.getInstance("SHA1");
            byte[] publicKey = md.digest(cert);
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < publicKey.length; i++) {
                String appendString = Integer.toHexString(0xFF & publicKey[i])
                                             .toUpperCase(Locale.US);
				if (appendString.length() == 1) { hexString.append("0"); }
                hexString.append(appendString);
                hexString.append(":");
            }
            String result = hexString.toString();
            return result.substring(0, result.length() - 1);
        }
        catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static boolean isNetWorkAvailable() {
        ConnectivityManager manager = (ConnectivityManager)GlobalConfiguration.getInstance()
                                                                              .getSystemService(
                                                                                      Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = manager != null ? manager.getActiveNetworkInfo() : null;
        return null != info && info.isAvailable();
    }

    /**
     * 获取当前app的应用名字
     */
    public static String getApplicationName(Context context) {
        //		AppUtils.getAppName();
        PackageManager packageManager = null;
        ApplicationInfo applicationInfo = null;
        try {
            packageManager = context.getApplicationContext().getPackageManager();
            applicationInfo = packageManager.getApplicationInfo(context.getPackageName(), 0);
        }
        catch (PackageManager.NameNotFoundException e) {
            applicationInfo = null;
        }
        String applicationName = (String)packageManager.getApplicationLabel(applicationInfo);
        return applicationName;
    }

    /**
     * 通过URI方式调起高德地图app
     */
    public static void startAMap(Activity activity, String title, double lat, double lng) {
        // 安装高德地图直接调用app,未安装则开启网页版地图导航
        if (getAppIn()) {
            Intent intent = new Intent("android.intent.action.VIEW", android.net.Uri.parse(
                    "androidamap://viewMap?sourceApplication=" + AppUtils.getAppName() + "&poiname=" + title + "&lat=" + lat + "&lon=" + lng + "&dev=0"));
            intent.setPackage("com.autonavi.minimap");
            activity.startActivity(intent);
        }
        else {
            String url = "http://mo.amap.com/?dev=0&q=" + lat + "," + lng + "&name=" + title;
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse(url));
            activity.startActivity(intent);
        }
    }

    /**
     * 判断高德地图app是否已经安装
     */
    public static boolean getAppIn() {
        return AppUtils.isAppInstalled("com.autonavi.minimap");
        //		PackageInfo packageInfo = null;
        //		try {
        //			packageInfo = getPackageManager().getPackageInfo(
        //					"com.autonavi.minimap", 0);
        //		} catch (NameNotFoundException e) {
        //			packageInfo = null;
        //			e.printStackTrace();
        //		}
        //		// 本手机没有安装高德地图app
        //		if (packageInfo != null) {
        //			return true;
        //		}
        //		// 本手机成功安装有高德地图app
        //		else {
        //			return false;
        //		}
    }

    /**
     * 开始导航
     * 注意示例：终点传入的是北京站坐标,但是POI的ID "B000A83M61"对应的是北京西站，所以实际算路以北京西站作为终点
     */
    public static void startNavigate(Context context, LatLng startLoc, LatLng endLoc,
                                     String endName, INaviInfoCallback callback) {
        Poi start = new Poi("我的位置", startLoc, "");

        Poi end = new Poi(endName, endLoc, "");
        AmapNaviPage.getInstance()
                    .showRouteActivity(context,
                            new AmapNaviParams(start, null, end, AmapNaviType.DRIVER), callback);
    }



    /**
     * 用SimpleDateFormat计算时间差
     * @throws ParseException
     */
    public static int calculateTimeDifferenceBySimpleDateFormat(String start, String end) {
        try {
            SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
            /*天数差*/
    //        Date fromDate1 = simpleFormat.parse("2018-03-01 12:00");
    //        Date toDate1 = simpleFormat.parse("2018-03-12 12:00");
    //        long from1 = fromDate1.getTime();
    //        long to1 = toDate1.getTime();
    //        int days = (int)((to1 - from1) / (1000 * 60 * 60 * 24));
    //        System.out.println("两个时间之间的天数差为：" + days);

            /*小时差*/
            Date fromDate2 = simpleFormat.parse(start);
            Date toDate2 = simpleFormat.parse(end);
            long from2 = fromDate2.getTime();
            long to2 = toDate2.getTime();
            int hours = (int)((to2 - from2) / (1000 * 60 * 60));
            System.out.println("两个时间之间的小时差为：" + hours);

            /*分钟差*/
    //        Date fromDate3 = simpleFormat.parse("2018-03-01 12:00");
    //        Date toDate3 = simpleFormat.parse("2018-03-12 12:00");
    //        long from3 = fromDate3.getTime();
    //        long to3 = toDate3.getTime();
    //        int minutes = (int)((to3 - from3) / (1000 * 60));
    //        System.out.println("两个时间之间的分钟差为：" + minutes);
            return hours;
            } catch (Exception e) {
                e.printStackTrace();
                return 0;
            }
    }

}
